/**
 * 全局变量
 */
var manyRichUE;
var manyRichUploader;
var isClick = true;
var mid = '';
$(function() {
	activeNav($("#info-weixinMenu"));
	
	var pBody = $(".pBody").height();
	var pBottom = $(".pBottom").height();
	$(".pContent").css({height: (pBody-pBottom-31) + "px"});
	
	$(window).resize(function() {
		var pBody = $(".pBody").height();
		var pBottom = $(".pBottom").height();
		$(".pContent").css({height: (pBody-pBottom-31) + "px"});
	});
	
	var setting = {
		data: {
			simpleData: {
				enable: true
			}
		},
		async:{
			enable: true,
			dataType: "json",
			type: "post",
			url: ctx + "/admin/weixinMenu/ajaxWeixinMenu",
			dataFilter: ajaxDataFilter
		},
		view: {
			addHoverDom: addHoverDom,
			removeHoverDom: removeHoverDom,
			selectedMulti: false
		},
		callback : {
			beforeAsync:function(){
				$("#treeBody").mask("加载中...");
			},
			onAsyncSuccess: function(){
				$("#treeBody").unmask();
			},
			onAsyncError: function(){
				$("#treeBody").unmask();
			},
			onClick: zTreeOnClick,
			onDrop: zTreeOnDrop,
			beforeDrag: function(treeId, treeNodes){
				if( treeNodes[0].level == 0 ){
					return false;
				}
				return true;
			},
			beforeDrop: function(treeId, treeNodes, targetNode, moveType){
				if(targetNode != null){
					if(targetNode.level > 0){
						return true;
					}
				}
				return false;
			}
		},
		edit: {
			enable: true,
			showRemoveBtn: false,
			showRenameBtn: false,
			drag: {
				autoExpandTrigger: true,
				isCopy : false,
				isMove : true
			}
		}
	};
	$.fn.zTree.init($("#menuTree"), setting);
	
	$("#menu-cancel").click(hideDialog);
	
	$("#menu-close").click(hideDialog);
	
	$("#reType").change(changeReType);
	
	$("#content-publish").click(publish);
	
	manyRichFunction();
	
	$("#word-content-save").click(function(){
		if(mid.length == 0){
			$.alert({message:'请选择一个子菜单后再操作'});
			return;
		}
		var wordContent = $('#wordContent').val();
		var reType = $('#reType').val();
		var id = $('#content-id').val();
		var data = {
			id:id,
			mid:mid,
			reType: reType,
			content: wordContent
		};
		$.post(ctx + "/admin/weixinMenu/ajaxMenuContentSave", data, function (result) {
			$.alert({ message: result.message});
			$.fn.zTree.getZTreeObj('menuTree').reAsyncChildNodes(null, "refresh");
		});
	});
	
	$('#webUrl-content-save').click(function(){
		if(mid.length == 0){
			$.alert({message:'请选择一个子菜单后再操作'});
			return;
		}
		var webUrl = $('#webUrl').val();
		var reType = $('#reType').val();
		var id = $('#content-id').val();
		var data = {
			id:id,
			mid:mid,
			reType: reType,
			url: webUrl
		};
		$.post(ctx + "/admin/weixinMenu/ajaxMenuContentSave", data, function (result) {
			$.alert({ message: result.message});
			$.fn.zTree.getZTreeObj('menuTree').reAsyncChildNodes(null, "refresh");
		});
	});
});

/**
 * 异步加载数据过滤
 * @param treeId
 * @param parentNode
 * @param responseData
 * @returns {Array}
 */
function ajaxDataFilter(treeId, parentNode, responseData) {
    var rd = [];
    $.each(responseData.data, function (i, n) {
    	rd.push({
    		id			: n.id,
    		name		: n.name + (n.level == 0 ? "" : "（" + (n.enabled ? "启用" : "停用") + "）"),
    		pId 		: n.parentid,
    		level		: n.level,
    		reType		: n.reType,
    		iconSkin	: "deptIcon",
    		value		: n.name,
    		enabled		: n.enabled,
    		orderIndex  : n.orderIndex
    	});
    });
    return rd;
}
/**
 * 树获取焦点
 * @param treeId
 * @param treeNode
 */
function addHoverDom(treeId, treeNode) {
	var sObj = $("#" + treeNode.tId + "_span");
	if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
	var addStr = "<span class='button add' id='addBtn_" + treeNode.tId 
				+ "' title='新增' onfocus='this.blur();'></span>";
	var editStr = "<span class='button edit' id='editBtn_" + treeNode.tId 
				+ "' title='重命名' onfocus='this.blur();'></span>";
	var removeStr = "<span class='button remove' id='removeBtn_" + treeNode.tId 
				+ "' title='删除' onfocus='this.blur();'></span>";
	if(treeNode.isParent || treeNode.level == 0){
		sObj.after(editStr);
		sObj.after(addStr);
	}else{
		sObj.after(removeStr);
		sObj.after(editStr);
		sObj.after(addStr);
	}
	
	var addBtn = $("#addBtn_" + treeNode.tId);
	if (addBtn) addBtn.click(function() {
		isClick = false;
		$('#menu-title').text("新建菜单");
		$("#menu-body").show();
		$('#menuName').focus();
		$('#enabled-true').prop("checked", true);
		$('#enabled-true').parent().addClass('active');

		if(treeNode.level == 0){
			$('#enabled-box').hide();
		}
		
		var path = treeNode.value;
		var p = treeNode.getParentNode();
		while (p){
			path = p.value + " &raquo; " + path;
			p = p.getParentNode();
		}
		$('#parentMenu').html(path);
		
		var orderIndex;//排序
		if(treeNode.isParent){
			orderIndex = treeNode.children.length + 1;
		}else{
			orderIndex = 1;
		}
		
		$("#menu-save").click(function(){
			var menuName = $('#menuName').val().trim();
			if(menuName.length == 0){
				$('#menuName').focus();
				return;
			}
			var enabled = $('#enabled-group input:checked').val();
			var datas = {
				name : menuName,
				parentid : treeNode.id,
				orderIndex: orderIndex,
				enabled: enabled,
				level: treeNode.level + 1
			};
			ajaxPostMenu(ctx + '/admin/weixinMenu/ajaxMenuCreate', datas, treeId);
		});
	});
	
	var editBtn = $("#editBtn_" + treeNode.tId);
	if (editBtn) editBtn.click(function() {
		isClick = false;
		$('#menu-title').text("重命名");
		$("#menu-body").show();
		$('#menuName').focus();
		$('#menuName').val(treeNode.value);
		if(treeNode.level == 0){
			$('#enabled-box').hide();
		}
		if(treeNode.enabled){
			$('#enabled-true').prop("checked", true);
			$('#enabled-true').parent().addClass('active');
		}else{
			$('#enabled-false').prop("checked", true);
			$('#enabled-false').parent().addClass('active');
		}
		
		var path;
		var p = treeNode.getParentNode();
		while (p){
			if(path){
				path = p.value + " &raquo; " + path;
			}else{
				path = p.value;
			}
			p = p.getParentNode();
		}
		$('#parentMenu').html(path);

		$("#menu-save").click(function(){
			var menuName = $('#menuName').val().trim();
			if(menuName.length == 0){
				$('#menuName').focus();
				return;
			}
			var enabled = $('#enabled-group input:checked').val();
			var datas = {
				id: treeNode.id,
				name : menuName,
				orderIndex: treeNode.orderIndex,
				enabled: enabled,
				level: treeNode.level
			};
			ajaxPostMenu(ctx + '/admin/weixinMenu/ajaxMenuUpdate', datas, treeId);
		});
	});
	
	var removeBtn = $("#removeBtn_" + treeNode.tId);
	if (removeBtn) removeBtn.bind("click", function(){
		isClick = false;
		$.confirm({
			message: "确认删除菜单？",
			callback: function(){
				ajaxPostMenu(ctx + '/admin/weixinMenu/ajaxMenuDelete', { id:treeNode.id } , treeId);
			}
		});
	});
};
/**
 * 树焦点移开
 * @param treeId
 * @param treeNode
 */
function removeHoverDom(treeId, treeNode) {
	if($("#addBtn_" + treeNode.tId)){
		$("#addBtn_" + treeNode.tId).unbind().remove();
	}
	if($("#editBtn_" + treeNode.tId)){
		$("#editBtn_" + treeNode.tId).unbind().remove();
	}
	if($("#removeBtn_" + treeNode.tId)){
		$("#removeBtn_" + treeNode.tId).unbind().remove();
	}
};
/**
 * zTree点击事件
 */
function zTreeOnClick(event, treeId, treeNode, clickFlag){
	var treeObj = $.fn.zTree.getZTreeObj(treeId);
	//treeObj.cancelSelectedNode();
	if(isClick) {
		if(treeNode.isParent){
			treeObj.expandNode(treeNode, !treeNode.open, false);
			resetForm();
			$("#wordContent-group").hide();
			$("#webUrl-group").hide();
			$("#singleRich-group").hide();
			$("#manyRich-group").hide();
			$("#menuAttr").text('');
			mid = '';
		} else {
			var path = treeNode.value;
			var p = treeNode.getParentNode();
			while (p){
				path = p.value + " &raquo; " + path;
				p = p.getParentNode();
			}
			$('#menuAttr').html(path);
			mid = treeNode.id;
			if(treeNode.reType == null){
				resetForm();
			}else{
				$("#reType").val(treeNode.reType);
				changeReType ();
				$("#propertiesBody").mask("数据加载中...");
				$.post(ctx + '/admin/weixinMenu/ajaxWeixinMenuContent', {mid: mid}, function (result) {
					$("#propertiesBody").unmask();
					var data = result.data;
					var id = null;
					var content = null;
					var title = null;
					var introducte = null;
					var thumbnailUrl = null;
					var url = null;
					if (data.length > 0) {
						id = data[0].id;
						content = data[0].content;
						title = data[0].title;
						introducte = data[0].introducte;
						thumbnailUrl = data[0].thumbnailUrl;
						url = data[0].url;
					}
					switch (treeNode.reType) {
						case 0: 
							$('#content-id').val(id);
							$('#webUrl').val(url);
							break;
						case 1: 
							$('#content-id').val(id);
							$("#wordContent").val(content);
							break;
						case 2: 
							$("#singleRichTitle").val(title);
							$("#singleRichintroducte").val(introducte);
							$("#singleRichContent").val(content);
							break;
						case 3:
							$(data).each(function(i , menuCount){
								$('#js_appmsg_preview').append(itemHTML(menuCount.id, menuCount));
								itemFunction(menuCount.id);
							});
							$('#manyRich-title').focus();
							$('#manyRich-title').val(title);
							$('#manyRich-introducte').val(introducte);
							$('#content-id').val(id);
							manyRichImageHtml(thumbnailUrl, true);
							if(content != null){
								manyRichUE.setContent(content);
							}else{
								manyRichUE.setContent('');
							}
							break;
						case 4:
							break;
					}
				});
			}
		}
	}
	isClick = true;
}
/**
 * 拖拽
 * @param event
 * @param treeId
 * @param treeNodes
 * @param targetNode
 * @param moveType
 */
function zTreeOnDrop(event, treeId, treeNodes, targetNode, moveType) {
	var treeObj = $.fn.zTree.getZTreeObj(treeId);
	var treeNode = treeNodes[0];
	var index = treeObj.getNodeIndex(treeNode);
	var datas = {
		id: treeNode.id,
		name : treeNode.value,
		orderIndex: index + 1,
		parentid: treeNode.pId,
		enabled: treeNode.enabled,
		level: treeNode.level
	};
	ajaxPostMenu(ctx + '/admin/weixinMenu/ajaxMenuDrop', datas, treeId);
};
/**
 * 重置表单
 */
function resetForm(){
	$("#reType").val(0);
	$("#webUrl-group").show();
	$("#wordContent-group").hide();
	$("#singleRich-group").hide();
	$("#manyRich-group").hide();
	$('#menu-properties-form')[0].reset();
	$('#js_appmsg_preview').html('');
	$('#content-id').val('');
	$('#manyRich-image').val('');
	manyRichUploader.reset();
	manyRichUE.setContent('');
	manyRichImageHtml('',true);
}
/**
 * 响应类型改变事件
 */
function changeReType () {
	var reType = parseInt($("#reType").val());
	resetForm();
	$("#reType").val(reType);
	switch (reType) {
	case 0: // 网络链接
		$("#webUrl-group").show();
		$("#wordContent-group").hide();
		$("#singleRich-group").hide();
		$("#manyRich-group").hide();
		break;
	case 1: // 纯文字消息
		$("#wordContent-group").show();
		$("#webUrl-group").hide();
		$("#singleRich-group").hide();
		$("#manyRich-group").hide();
		break;
	case 2: // 单图文消息
		$("#singleRich-group").show();
		$("#wordContent-group").hide();
		$("#webUrl-group").hide();
		$("#manyRich-group").hide();
		break;
	case 3: // 多图文消息
		$("#manyRich-group").show();
		$("#singleRich-group").hide();
		$("#wordContent-group").hide();
		$("#webUrl-group").hide();
		break;
	}
}

/**
 * 隐藏部门弹出框
 */
function hideDialog () {
	$("#menu-body").hide();
	$('#menuName').val('');
	$("#menu-save").unbind();
	$('#parentMenu').html('');
	$('#enabled-group .active').removeClass('active');
	$('#enabled-group input:checked').prop("checked", false);
	$('#enabled-box').show();
}

/**
 * AJAX提交菜单信息
 */
function ajaxPostMenu(url, datas, treeId){
	$.ajax({
		async : false,
		cache : false,
		dataType : 'JSON',
		type : 'POST',
		url : url,
		data : datas,
		beforeSend : function(){
			$('#menu-form').mask("正在提交...");
		},
		success : function(data) {
			$('#menu-form').unmask();
			if(!data.success){
				$.alert({message: data.message});
			}
			hideDialog();
			var treeObj = $.fn.zTree.getZTreeObj(treeId);
			treeObj.reAsyncChildNodes(null, "refresh");
		},
		error : function() {
			$('#menu-form').unmask();
			$.alert({message: "操作异常，请稍候再试！"});
		}
	});
}
/**
 * 发布菜单
 */
function publish() {
	$.confirm({
		message: "确认要发布菜单？",
		callback: function(){
			$.post(ctx + "/admin/weixinMenu/ajaxWeixinMenuPublish", {}, function (result) {
				$.alert({ message: result.message});
			});
		}
	});
}

/**
 * 多图文事件
 */
function manyRichFunction(){
	$("#manyRich-group").show();
	manyRichUE = UE.getEditor('manyRich-wordContent');
	
	loadUploader();
	
	$('#js_add_appmsg').click(function(){
		if(mid.length == 0){
			$.alert({message:'请选择一个子菜单后再操作'});
			return;
		}
		if($('#js_appmsg_preview .js_appmsg_item').length > 7 ){
			$.alert({message:'最多只可以加入8条图文消息'});
			return;
		}
		//网络新增一条空的记录
		$.post(ctx + "/admin/weixinMenu/ajaxMenuContentCreate", {mid: mid}, function (result) {
			if(result.success){
				$('#js_appmsg_preview').append(itemHTML(result.data));
				itemFunction(result.data);
				$('#manyRich-title').focus();
				manyRichUploader.reset();
				manyRichUE.setContent('');
				manyRichImageHtml('',true);
				$('#content-id').val(result.data);
				$('#manyRich-title').val('');
				$('#manyRich-introducte').val('');
				$('#manyRich-image').val('');
				$.fn.zTree.getZTreeObj('menuTree').reAsyncChildNodes(null, "refresh");
			}else{
				$.alert({ message: result.message});
			}
		});
	});
	
	$('#manyRich-content-save').click(function(){
		if($('#content-id').val().length > 0){
			manyRichUploader.upload();
		}else{
			$.alert({message: '请在左边先点击编辑按钮再修改数据保存'});
		}
	});
	
	function loadUploader(){
		manyRichUploader = WebUploader.create({
		    auto: false,
		    swf : ctx + '/static/plugins/webuploader/Uploader.swf',
			server : ctx + "/api/upload/file",
		    pick: { id : '#manyRich-upload', multiple : false },
		    accept: {
		        title: 'Images',
		        extensions: 'gif,jpg,jpeg,bmp,png',
		        mimeTypes: 'image/*'
		    }
		});
		var t = setInterval(function(){
			var isTrue = $("#manyRich-upload").hasClass('webuploader-container');
			if(isTrue){
				clearInterval(t);
				$("#manyRich-group").hide();
				return;
			}
		},100);
		
		manyRichUploader.on( 'error', function( type ) {
			switch (type) {
				case 'Q_TYPE_DENIED':
					$.alert({message:'请选择正确的图片类型！'});
					break;
				case 'Q_EXCEED_SIZE_LIMIT':
					$.alert({message:'文件大小不能超过2MB！'});
					break;
				default:
					break;
			}
		});
		
		manyRichUploader.on( 'fileQueued', function( file  ) {
			uploaderFlag = true;
			var files = manyRichUploader.getFiles();
			if(files.length > 1){
				manyRichUploader.reset();
				manyRichUploader.addFiles( file );
			}
			manyRichUploader.makeThumb( file, function( error, src ) {
				manyRichImageHtml(src,false);
			});
		});
		
		manyRichUploader.on('uploadBeforeSend',function(object ,data , headers ){
			data.folder = "/manyRichImages/";
		});
		
		manyRichUploader.on( 'uploadAccept', function( object,ret ) {
			manyRichImageHtml(ret.filePath,true);
		});
		
		manyRichUploader.on( 'uploadFinished', function() {
			var reType = $('#reType').val();
			var id = $('#content-id').val();
			var title = $('#manyRich-title').val();
			var introducte = $('#manyRich-introducte').val();
			var thumbnailUrl = $('#manyRich-image').val();
			var content = manyRichUE.getContent();
			var data = {
				mid: mid,
				reType: reType,
				id: id,
				title: title,
				introducte: introducte,
				thumbnailUrl: thumbnailUrl,
				content: content
			};
			$.post(ctx + "/admin/weixinMenu/ajaxMenuContentSave", data, function (result) {
				$.alert({ message: result.message});
			});
		});
	}
}
/**
 * 图文：生成图片
 * @param src
 * @param server
 */
function manyRichImageHtml(src,server){
	if(src != '' && src != null) {
		var imgSrc = src;
		if(server){
			imgSrc = ctx + src;
			$('#manyRich-image').val(src);
		}
		var html = '<img src="' + imgSrc + '" height="100" width="180" />';
		$("#manyRich-fileList").html(html);
	}else{
		$("#manyRich-fileList").html('');
	}
}
/**
 * 图文：列表事件
 * @param id
 */
function itemFunction(id){
	$('#js_appmsg_preview .js_appmsg_item').each(function(i , div){
		if(parseInt($(this).attr('data-id')) == id ){
			$(this).find('.js_del').click(function(){
				var btn = $(this);
				//网络删除一条记录
				$.post(ctx + "/admin/weixinMenu/ajaxMenuContentDelete", {id: id}, function (result) {
					if(result.success){
						$(btn).parents('.js_appmsg_item').remove();
						manyRichUploader.reset();
						manyRichUE.setContent('');
						manyRichImageHtml('',true);
						$('#content-id').val(result.data);
						$('#manyRich-title').val('');
						$('#manyRich-introducte').val('');
						$('#manyRich-image').val('');
					}else{
						$.alert({ message: result.message});
					}
				});
			});
			
			$(this).find('.js_edit').click(function(){
				var btn = $(this);
				$('#manyRich-title').focus();
				manyRichUploader.reset();
				manyRichUE.setContent('');
				manyRichImageHtml('',true);
				$('#content-id').val('');
				$('#manyRich-title').val('');
				$('#manyRich-introducte').val('');
				$('#manyRich-image').val('');
				var firstId = $('#js_appmsg_preview .js_appmsg_item').first().attr('data-id');
				if(firstId == id){
					$('#manyRich-upload-jy').text('大图片建议尺寸：900像素 * 500像素');
				}else{
					$('#manyRich-upload-jy').text('小图片建议尺寸：200像素 * 200像素');
				}
				//网络查询一条记录并且填入右边文本框
				$.post(ctx + '/admin/weixinMenu/ajaxWeixinMenuContent', {mid: mid}, function (result) {
					$(result.data).each(function(i, data){
						if(id == data.id){
							$('#content-id').val(data.id);
							$('#manyRich-title').val(data.title);
							$('#manyRich-introducte').val(data.introducte);
							manyRichImageHtml(data.thumbnailUrl, true);
							if(data.content != null){
								manyRichUE.setContent(data.content);
							}else{
								manyRichUE.setContent('');
							}
						}
					});
				});
			});
		}
	});
}
/**
 * 图文：列表HTML
 * @param id
 * @returns
 */
function itemHTML(id, menuCotent){
	var title = '标题';
	var thumb = '';
	var has_thumb = '';
	if(menuCotent){
		if(menuCotent.title != null){
			title = menuCotent.title;
		}
		if(menuCotent.thumbnailUrl != null){
			thumb = menuCotent.thumbnailUrl;
			has_thumb = 'has_thumb';
		}
	}
	var html1 = new Array();
	html1.push('<div id="appmsgItem' + id + '" class="js_appmsg_item ' + has_thumb + '" data-id="' + id + '" data-fileid="">');
	html1.push('<div class="appmsg_info">');
	html1.push('<em class="appmsg_date"></em>');
	html1.push('</div>');
	html1.push('<div class="cover_appmsg_item">');
	html1.push('<h4 class="appmsg_title">');
	html1.push('<a target="_blank" onclick="return false;" href="javascript:void(0);">' + title + '</a>');
	html1.push('</h4>');
	html1.push('<div class="appmsg_thumb_wrp">');
	html1.push('<img class="js_appmsg_thumb appmsg_thumb" src="' + thumb + '">');
	html1.push('<i class="appmsg_thumb default">封面图片</i>');
	html1.push('</div>');
	html1.push('<div class="appmsg_edit_mask">');
	html1.push('<a class="icon18_common edit_gray js_edit" href="javascript:;" data-id="' + id + '" onclick="return false;">编辑</a>');
	html1.push('</div>');
	html1.push('</div>');
	html1.push('</div>');
	
	var html2 = new Array();
	html2.push('<div id="appmsgItem' + id + '" class="appmsg_item js_appmsg_item ' + has_thumb + '" data-id="' + id + '" data-fileid="">');
	html2.push('<img class="js_appmsg_thumb appmsg_thumb" src="' + thumb + '">');
	html2.push('<i class="appmsg_thumb default">缩略图</i>');
	html2.push('<h4 class="appmsg_title">');
	html2.push('<a target="_blank" href="javascript:void(0);" onclick="return false;">' + title + '</a>');
	html2.push('</h4>');
	html2.push('<div class="appmsg_edit_mask">');
	html2.push('<a class="icon18_common edit_gray js_edit" href="javascript:void(0);" onclick="return false;" data-id="' + id + '">编辑</a>');
	html2.push('<a class="icon18_common del_gray js_del" href="javascript:void(0);" onclick="return false;" data-id="' + id + '">删除</a>');
	html2.push('</div>');
	html2.push('</div>');
	
	if($('#js_appmsg_preview .js_appmsg_item').length > 0){
		return html2.join('');
	}else{
		return html1.join('');
	}
}
